<!-- filename: pages/playlist/playlist.vue -->
<template>
  <!-- 全局 Header -->
  <Header @open-auth-modal="isAuthModalVisible = true" />
  <AuthModal v-if="isAuthModalVisible" @close="isAuthModalVisible = false" />

  <view class="page-container" style="padding-top: 60px;">
    <view class="content-wrapper">
      
      <!-- 【核心修正】将 v-if/v-else 作为最外层逻辑 -->

      <!-- 如果用户已登录，显示完整页面 -->
      <view v-if="authStore.isLoggedIn">
        <!-- 公共歌单区域 -->
        <div class="public-playlists-section">
          <div class="section-header">
            <h2 class="section-title">精选歌单</h2>
            <view class="more-btn" @click="navigateToPublicPlaylists">更多 ›</view>
          </div>
          <view v-if="publicPlaylistsLoading" class="loading-state small">加载中...</view>
          <view v-else-if="publicPlaylists.length === 0" class="empty-state small">暂无公共歌单</view>
          <view v-else class="public-playlist-grid">
            <view v-for="p in publicPlaylists" :key="p.id" class="public-playlist-card">
              <view class="share-btn" @click.stop="handleShare(p.id, p.name)">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M18 16.08c-.76 0-1.44.3-1.96.77L8.91 12.7c.05-.23.09-.46.09-.7s-.04-.47-.09-.7l7.05-4.11c.54.5 1.25.81 2.04.81 1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3c0 .24.04.47.09.7L8.04 9.81C7.5 9.31 6.79 9 6 9c-1.66 0-3 1.34-3 3s1.34 3 3 3c.79 0 1.5-.31 2.04-.81l7.12 4.16c-.05.21-.08.43-.08.65 0 1.66 1.34 3 3 3s3-1.34 3-3-1.34-3-3-3z"/></svg>
              </view>
              <view class="clone-btn" @click.stop="handleClonePlaylist(p.id)">
                 <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M14.47 13.53L12.04 11.1l2.43-2.43-1.41-1.41-2.43 2.43-1.29-1.29-.71.71 1.29 1.29-2.43 2.43 1.41 1.41 2.43-2.43 1.29 1.29.71-.71-1.29-1.29zM19 3h-4.18C14.4 1.84 13.3 1 12 1s-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7-.25c.41 0 .75.34.75.75s-.34.75-.75.75-.75-.34-.75-.75.34-.75.75-.75zM19 19H5V5h14v14z"/></svg>
              </view>
              <view class="cover-wrapper" @click="navigateToPublicDetail(p.id)">
                <image v-if="p.cover_url" :src="p.cover_url" class="cover-image" mode="aspectFill" />
                <view v-else class="cover-placeholder music-icon">
                  <svg width="30" height="30" viewBox="0 0 24 24" fill="currentColor"><path d="M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z"/></svg>
                </view>
              </view>
              <view class="playlist-info" @click="navigateToPublicDetail(p.id)">
                <text class="playlist-name">{{ p.name }}</text>
                <text class="creator-name">上传者: {{ p.username }}</text>
              </view>
            </view>
          </view>
        </div>

        <!-- 个人歌单区域 -->
        <div>
          <div class="page-header">
            <h1 class="page-title">我的歌单</h1>
            <div v-if="playlists.length > 0" class="action-btn edit-btn" @click="toggleEditMode">
              {{ isEditMode ? '完成' : '编辑排序' }}
            </div>
          </div>
          <view class="playlist-card special-card" @click="navigateToPlaylistDetail(-1, '我喜欢的音乐')">
            <view class="cover-placeholder">
              <svg width="40" height="40" viewBox="0 0 24 24" fill="currentColor"><path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/></svg>
            </view>
            <view class="playlist-info">
              <text class="playlist-name">我喜欢的音乐</text>
              <text class="song-count">{{ likedSongsCount }} 首</text>
            </view>
          </view>
          <view v-if="isLoading" class="loading-state">正在加载歌单...</view>
          <view v-else-if="playlists.length === 0" class="empty-state">
            <text>您还没有创建任何歌单</text>
            <text class="tip">可以去歌曲的菜单中“添加到歌单”来创建哦</text>
          </view>
          <view v-else class="playlist-grid" :class="{ 'edit-mode-active': isEditMode }" @dragover.prevent="handleDragOver" @drop.prevent="handleDrop">
            <view v-for="(playlist, index) in playlists" :key="playlist.id" class="playlist-card-wrapper" :class="{ 'dragging-source': dragIndex === index }" :draggable="isEditMode" @dragstart="handleDragStart(index, $event)" @dragend="handleDragEnd" @dragenter.prevent="handleDragEnter(index, $event)">
              <view class="playlist-card">
                <view v-if="!playlist.is_public" class="publish-btn" @click.stop="handlePublish(playlist.id)">
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M9 16h6v-6h4l-7-7-7 7h4v6zm-4 2h14v2H5v-2z"/></svg>
                </view>
                <view class="delete-btn" @click.stop="handleDelete(playlist.id, playlist.name)">
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/></svg>
                </view>
                <view class="cover-wrapper" @click="navigateToPlaylistDetail(playlist.id, playlist.name)">
                  <image v-if="playlist.cover_url" :src="playlist.cover_url" class="cover-image" mode="aspectFill"/>
                  <view v-else class="cover-placeholder music-icon">
                    <svg width="30" height="30" viewBox="0 0 24 24" fill="currentColor"><path d="M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z"/></svg>
                  </view>
                </view>
                <view class="playlist-info" @click="navigateToPlaylistDetail(playlist.id, playlist.name)">
                  <text class="playlist-name">{{ playlist.name }}</text>
                  <text class="song-count">{{ playlist.song_count }} 首</text>
                </view>
              </view>
            </view>
          </view>
        </div>
      </view>

      <!-- 如果用户未登录，显示公共歌单和登录提示 -->
      <view v-else>
        <!-- 公共歌单区域 -->
        <div class="public-playlists-section">
          <div class="section-header">
            <h2 class="section-title">精选歌单</h2>
            <view class="more-btn" @click="navigateToPublicPlaylists">更多 ›</view>
          </div>
          <view v-if="publicPlaylistsLoading" class="loading-state small">加载中...</view>
          <view v-else-if="publicPlaylists.length === 0" class="empty-state small">暂无公共歌单</view>
          <view v-else class="public-playlist-grid">
            <view v-for="p in publicPlaylists" :key="p.id" class="public-playlist-card">
              <view class="share-btn" @click.stop="handleShare(p.id, p.name)">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M18 16.08c-.76 0-1.44.3-1.96.77L8.91 12.7c.05-.23.09-.46.09-.7s-.04-.47-.09-.7l7.05-4.11c.54.5 1.25.81 2.04.81 1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3c0 .24.04.47.09.7L8.04 9.81C7.5 9.31 6.79 9 6 9c-1.66 0-3 1.34-3 3s1.34 3 3 3c.79 0 1.5-.31 2.04-.81l7.12 4.16c-.05.21-.08.43-.08.65 0 1.66 1.34 3 3 3s3-1.34 3-3-1.34-3-3-3z"/></svg>
              </view>
              <view class="clone-btn" @click.stop="handleClonePlaylist(p.id)">
                 <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M14.47 13.53L12.04 11.1l2.43-2.43-1.41-1.41-2.43 2.43-1.29-1.29-.71.71 1.29 1.29-2.43 2.43 1.41 1.41 2.43-2.43 1.29 1.29.71-.71-1.29-1.29zM19 3h-4.18C14.4 1.84 13.3 1 12 1s-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7-.25c.41 0 .75.34.75.75s-.34.75-.75.75-.75-.34-.75-.75.34-.75.75-.75zM19 19H5V5h14v14z"/></svg>
              </view>
              <view class="cover-wrapper" @click="navigateToPublicDetail(p.id)">
                <image v-if="p.cover_url" :src="p.cover_url" class="cover-image" mode="aspectFill" />
                <view v-else class="cover-placeholder music-icon">
                  <svg width="30" height="30" viewBox="0 0 24 24" fill="currentColor"><path d="M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z"/></svg>
                </view>
              </view>
              <view class="playlist-info" @click="navigateToPublicDetail(p.id)">
                <text class="playlist-name">{{ p.name }}</text>
                <text class="creator-name">上传者: {{ p.username }}</text>
              </view>
            </view>
          </view>
        </div>
        
        <!-- 登录提示 -->
        <view class="login-prompt">
          <h1 class="prompt-title">请先登录</h1>
          <p class="prompt-text">登录后即可创建和管理您的专属歌单。</p>
          <button class="prompt-btn" @click="isAuthModalVisible = true">
            前往注册 / 登录
          </button>
        </view>
      </view>

    </view>
  </view>
  <Player v-if="playerStore.showPlayer" />
</template>

<script setup>
import { ref } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import { useAuthStore } from '@/store/auth';
import { usePlayerStore } from '@/store/player';
import { request } from "@/utils/request"; // 【核心修改1】

import Header from '@/components/Header/Header.vue';
import AuthModal from '@/components/AuthModal/AuthModal.vue';
import Player from '@/components/Player.vue';

const authStore = useAuthStore();
const playerStore = usePlayerStore();
const isAuthModalVisible = ref(false);

const playlists = ref([]);
const likedSongsCount = ref('...');
const isLoading = ref(true);
const publicPlaylists = ref([]);
const publicPlaylistsLoading = ref(true);

// 【核心修改2】不再需要 API_BASE_URL
// const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;

const isEditMode = ref(false);
const dragIndex = ref(null);
const dropIndex = ref(null);

// --- 【核心修改3】重写所有 API 请求函数 ---

const fetchPublicPlaylists = async () => {
  publicPlaylistsLoading.value = true;
  try {
    const data = await request({
      url: `/api/public/playlists?page=1&limit=4`,
      method: 'GET'
    });
    if (data && data.playlists) {
      publicPlaylists.value = data.playlists;
    }
  } catch (error) {
    console.error("Failed to fetch public playlists:", error);
  } finally {
    publicPlaylistsLoading.value = false;
  }
};

const handlePublish = (playlistId) => {
  uni.showModal({
    title: '确认发布',
    content: '您确定要将此歌单发布为公共歌单吗？发布后，所有用户都将可以看到它。',
    success: async (res) => {
      if (res.confirm) {
        uni.showLoading({ title: '发布中...' });
        try {
          await request({
            url: `/api/playlists/${playlistId}/publish`,
            method: 'POST',
          });
          uni.showToast({ title: '发布成功', icon: 'success' });
          fetchMyPlaylists();
          fetchPublicPlaylists();
        } catch (error) {
          uni.showToast({ title: '操作失败', icon: 'none' });
        } finally {
          uni.hideLoading();
        }
      }
    }
  });
};

const fetchMyPlaylists = async () => {
  isLoading.value = true;
  try {
    const data = await request({
      url: `/api/playlists/mine`,
      method: 'GET'
    });
    if (Array.isArray(data)) {
      playlists.value = data;
    }
  } catch (error) {
    console.error("Failed to fetch my playlists:", error);
  } finally {
    isLoading.value = false;
  }
};

const fetchLikedSongsCount = async () => {
  likedSongsCount.value = '...';
  try {
    const data = await request({
      url: `/api/users/stats/liked-songs-count`,
      method: 'GET'
    });
    likedSongsCount.value = data.count;
  } catch (error) {
    likedSongsCount.value = 0;
  }
};

const handleClonePlaylist = (playlistId) => {
  if (!authStore.isLoggedIn) {
    isAuthModalVisible.value = true;
    return;
  }
  uni.showModal({
    title: '确认克隆',
    content: '是否要将此歌单复制一份到您的“我的歌单”中？',
    success: async (res) => {
      if (res.confirm) {
        uni.showLoading({ title: '正在复制...' });
        try {
          await request({
            url: `/api/public/playlists/${playlistId}/clone`,
            method: 'POST',
          });
          uni.showToast({ title: '已复制到我的歌单', icon: 'success' });
          fetchMyPlaylists();
        } catch (error) {
          const errorMsg = error?.data?.error || '复制失败';
          uni.showToast({ title: errorMsg, icon: 'none' });
        } finally {
          uni.hideLoading();
        }
      }
    }
  });
};

const handleDelete = (playlistId, playlistName) => {
  uni.showModal({
    title: '确认删除',
    content: `您确定要删除歌单「${playlistName}」吗？此操作不可恢复。`,
    success: async (res) => {
      if (res.confirm) {
        uni.showLoading({ title: '删除中...' });
        try {
          await request({
            url: `/api/playlists/${playlistId}`,
            method: 'DELETE',
          });
          uni.showToast({ title: '删除成功', icon: 'success' });
          playlists.value = playlists.value.filter(p => p.id !== playlistId);
          fetchPublicPlaylists();
        } catch (error) {
          const errorMsg = error?.data?.error || '删除失败';
          uni.showToast({ title: errorMsg, icon: 'none' });
        } finally {
          uni.hideLoading();
        }
      }
    }
  });
};

const saveOrder = async () => {
  const playlist_ids = playlists.value.map(p => p.id);
  uni.showLoading({ title: '保存中...' });
  try {
    await request({
      url: `/api/playlists/order`,
      method: 'PUT',
      data: { playlist_ids },
    });
    uni.showToast({ title: '排序已保存', icon: 'success' });
  } catch (error) {
    uni.showToast({ title: '保存失败', icon: 'error' });
  } finally {
    uni.hideLoading();
  }
};


// --- 无需修改的函数 ---
onShow(() => {
  fetchPublicPlaylists();
  if (authStore.isLoggedIn) {
    fetchMyPlaylists();
    fetchLikedSongsCount();
  } else {
    playlists.value = [];
    likedSongsCount.value = 0;
    isLoading.value = false;
  }
});

const navigateToPublicPlaylists = () => {
  uni.navigateTo({ url: '/pages/public-playlists/public-playlists' });
};

const navigateToPublicDetail = (id) => {
  uni.navigateTo({
    url: `/pages/public-playlist-detail/public-playlist-detail?id=${id}`
  });
};

const handleShare = async (playlistId, playlistName) => {
  const url = `${window.location.origin}/#/pages/public-playlist-detail/public-playlist-detail?id=${playlistId}`;
  const shareData = {
    title: `分享歌单: ${playlistName || '精选歌单'}`,
    text: `快来听听《${playlistName || '精选歌单'}》`,
    url: url,
  };
  if (navigator.share) {
    try {
      await navigator.share(shareData);
    } catch (err) {
      if (err.name !== 'AbortError') console.error("分享失败:", err);
    }
  } else {
    try {
      await navigator.clipboard.writeText(url);
      uni.showToast({ title: "分享链接已复制到剪贴板", icon: "none" });
    } catch (err) {
      uni.showToast({ title: "复制链接失败", icon: "error" });
    }
  }
};

const navigateToPlaylistDetail = (id, name) => {
  if (isEditMode.value) return;
  uni.navigateTo({
    url: `/pages/playlist-detail/playlist-detail?id=${id}&name=${encodeURIComponent(name)}`
  });
};

const toggleEditMode = () => {
  isEditMode.value = !isEditMode.value;
  if (!isEditMode.value) {
    saveOrder();
  }
};

const handleDragStart = (index, event) => {
  dragIndex.value = index;
};

const handleDragEnter = (index, event) => {
  if (index === dragIndex.value) return;
  dropIndex.value = index;
  const itemToMove = playlists.value.splice(dragIndex.value, 1)[0];
  playlists.value.splice(index, 0, itemToMove);
  dragIndex.value = index;
};

const handleDragOver = (event) => {};
const handleDrop = () => { handleDragEnd(); };
const handleDragEnd = () => { dragIndex.value = null; dropIndex.value = null; };

</script>

<style scoped lang="scss">
/* --- 页面基础布局 --- */
.page-container {
  display: flex;
  justify-content: center;
  width: 100%;
  min-height: 100vh;
  background-color: #f8f8f8;
}
.content-wrapper {
  width: 100%;
  max-width: 800px;
  padding: 20px;
  padding-bottom: 150px; /* 为底部播放器和导航栏留出空间 */
}

/* --- 统一的头部样式 --- */
.page-header,
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.page-title,
.section-title {
  font-size: 24px;
  font-weight: bold;
}
.more-btn {
  font-size: 14px;
  color: #888;
  cursor: pointer;
}
.action-btn {
  padding: 8px 16px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
}
.edit-btn {
  background-color: #007aff;
  color: white;
  &:hover {
    background-color: #0056b3;
  }
}

/* --- 公共歌单区域 --- */
.public-playlists-section {
  margin-bottom: 40px;
  border-bottom: 1px solid #eee;
  padding-bottom: 30px;
}

/* --- 登录提示 --- */
.login-prompt {
  margin-top: 20px;
  text-align: center;
  padding: 40px;
  background-color: #f9f9f9;
  border-radius: 12px;
}
.prompt-title {
  font-size: 22px;
  margin-bottom: 15px;
}
.prompt-text {
  color: #666;
  margin-bottom: 30px;
}
.prompt-btn {
  background-color: #007aff;
  color: white;
  &::after {
    border: none;
  }
}

/* --- 加载和空状态 --- */
.loading-state,
.empty-state {
  text-align: center;
  color: #888;
  padding: 50px 0;
}
.loading-state.small,
.empty-state.small {
  padding: 20px 0;
  font-size: 14px;
}
.empty-state .tip {
  display: block;
  font-size: 14px;
  color: #aaa;
  margin-top: 10px;
}

/* --- 【核心重构】统一的网格和卡片样式 --- */

/* 统一的网格布局 */
.public-playlist-grid,
.playlist-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 20px;
}

/* 统一的卡片基础样式 (适用于 public-playlist-card 和 playlist-card) */
.public-playlist-card,
.playlist-card {
  position: relative;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

    /* 桌面端悬浮时显示按钮 */
    .publish-btn, .delete-btn, .share-btn, .clone-btn {
      opacity: 1;
    }
  }

  /* 在触摸设备上，按钮始终可见 */
  @media (hover: none) {
    .publish-btn, .delete-btn, .share-btn, .clone-btn {
      opacity: 1;
    }
  }
}

/* “我喜欢的音乐”特殊卡片样式 */
.special-card {
  display: flex;
  align-items: center;
  padding: 20px;
  margin-bottom: 20px;
  background: #56aeff;
  color: white;
  .playlist-name {
    color: white;
  }
  .song-count {
    color: rgba(255, 255, 255, 0.8);
  }
}
.special-card .cover-placeholder {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  flex-shrink: 0;
  margin-right: 20px;
  background: #85c4ff;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 统一的按钮样式 */
.publish-btn, .delete-btn, .share-btn, .clone-btn {
  position: absolute;
  top: 8px;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2;
  opacity: 0; /* 默认在桌面端隐藏 */
  transition: opacity 0.2s;
  cursor: pointer;
  color: white;
}
.publish-btn {
  left: 8px;
  background-color: rgba(0, 122, 255, 0.8);
}
.delete-btn {
  right: 8px;
  background-color: rgba(0, 0, 0, 0.4);
  &:hover {
    background-color: rgba(229, 36, 94, 0.8);
  }
}
.share-btn {
  right: 8px;
  background-color: rgba(0, 122, 255, 0.8);
}
.clone-btn {
  left: 8px;
  background-color: rgba(0, 122, 255, 0.8);
}

/* 统一的封面样式 */
.cover-wrapper {
  width: 100%;
  padding-top: 100%;
  position: relative;
  background-color: #f0f0f0;
}
.cover-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
.cover-placeholder.music-icon {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  svg {
    color: #aaa;
  }
}

/* 统一的文字信息样式 */
.playlist-info {
  padding: 15px;
}
.playlist-name {
  display: block;
  font-weight: 500;
  font-size: 16px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.song-count, .creator-name {
  display: block;
  font-size: 12px;
  color: #888;
  margin-top: 5px;
}

/* 拖拽相关样式 */
.playlist-grid.edit-mode-active {
  border: 2px dashed #007aff;
  padding: 10px;
  border-radius: 12px;
}
.playlist-card-wrapper {
  transition: transform 0.2s ease;
}
.edit-mode-active .playlist-card-wrapper {
  cursor: grab;
}
.edit-mode-active .playlist-card-wrapper:active {
  cursor: grabbing;
}
.dragging-source {
  transform: scale(1.05);
  opacity: 0.5;
}
</style>